<template>
	<view class="container">
		<!-- 系统消息 -->
		<view class="conversations">
			<view>
				<view class="scroll-item system flex">
					<view>
						<uni-badge class="uni-badge-left-margin" :text="count" absolute="rightTop" :offset="[10, 10]"
							size="small">
							<view class="item-head">
								<image mode="widthFix" src="/static/images/home/notification.png"></image>
								<!--                <uni-icons type="notification" size="40"></uni-icons>-->
							</view>
						</uni-badge>
					</view>
					<view class="scroll-item_info" @click="noticeClick">
						<view class="item-info-top flex space-between">
							<text class="item-info-top_name">系统消息</text>
						</view>
					</view>
				</view>
			</view>
		</view>
		<MyLogin v-if="showlogin" :showlogin.sync="showlogin"></MyLogin>

		<!-- list列表 start -->
		<scroll-view class="conversations" scroll-y="true">
			<!-- 互动消息 -->
			<view class="scroll-item interact flex" @click="isActive = !isActive">
				<view>
					<view class="item-head">
						<image mode="widthFix" src="/static/images/home/intereaction.png"></image>
					</view>
				</view>
				<view class="scroll-item_info">
					<view class="item-info-top flex space-between">
						<view class="item-info-top_name">互动消息</view>
						<u-icon :name=" isActive ? 'arrow-down' : 'arrow-up'" color="#7CD1A5" size="25"></u-icon>
					</view>
				</view>
			</view>

			<view v-if="isActive">
				<view v-if="conversations.length > 0">
					<view class="scroll-item" v-for="(conversation, key) in conversations" :key="key">
						<view class="flex">
							<view>
								<view class="item-head_unread" v-if="conversation.unread">{{ conversation.unread }}
								</view>

								<view class="item-head">
									<image :src="conversation.data.avatar" class="head-icon"></image>

								</view>

							</view>
							<view class="scroll-item_info" @click="chat(conversation)">
								<view class="item-info-top flex space-between">
									<text class="item-info-top_name">{{ conversation.data.name }}

									</text>

									<view class="item-info-top_time">
										{{ formatDate(conversation.lastMessage.timestamp) }}</view>
								</view>
								<view class="item-info-bottom">
									<view class="item-info-bottom-item flex space-between">
										<view class="item-info-top_content" v-if="!conversation.lastMessage.recalled">
											<text class="unread-text">
												{{ conversation.lastMessage.read === false && conversation.lastMessage.senderId === userInfo.username ? '[未读]' : '' }}
											</text>

											<text v-if="conversation.lastMessage.senderId === userInfo.username">我: </text>
											<text
												v-else>{{ conversation.type === 'group' ? conversation.lastMessage.senderData.name : conversation.data.name }}:
											</text>
											<text
												v-if="conversation.lastMessage.type === 'text'">{{ conversation.lastMessage.payload.text }}</text>
											<text v-else-if="conversation.lastMessage.type === 'video'">[视频消息]</text>
											<text v-else-if="conversation.lastMessage.type === 'audio'">[语音消息]</text>
											<text v-else-if="conversation.lastMessage.type === 'image'">[图片消息]</text>
											<text v-else-if="conversation.lastMessage.type === 'file'">[文件消息]</text>
											<text v-else-if="conversation.lastMessage.type === 'order'">[订单]</text>
											<text v-else>[[未识别内容]]</text>
										</view>
										<view class="item-info-top_content" v-else>

											<text v-if="conversation.lastMessage.senderId === userInfo.username">
												你撤回了一条消息
											</text>
											<view v-else>
												{{ conversation.type === 'group' ? conversation.lastMessage.senderData.name : conversation.data.name }}
												撤回了一条消息
											</view>
										</view>
										<view class="item-info-bottom_action" @click.stop="showAction(conversation)">
										</view>
									</view>
								</view>
							</view>
						</view>
					</view>
				</view>
				<view class="no-conversation" v-else>~当前没有会话~</view>
			</view>


			<view class="action-container" v-if="actionPopup.visible">
				<view class="layer" @click="actionPopup.visible = false"></view>
				<view class="action-box">
					<view class="action-item" @click="topConversation">
						{{ actionPopup.conversation.top ? '取消置顶' : '置顶聊天' }}
					</view>
					<view class="action-item" @click="deleteConversation">删除聊天</view>
				</view>
			</view>
		</scroll-view>
		<!-- list列表 end -->

	</view>

</template>

<script>
	var self;
	import MyLogin from '@/components/my-login.vue'
	import {
		formatDate
	} from '../../lib/utils';
	import restApi from '../../lib/restapi';

	export default {
		name: 'conversation',
		components: {
			MyLogin
		},
		data() {
			return {
				isActive: true,
				mediaUrl: uni.$http.mediaUrl,
				userInfo: null,
				notifications: [],
				count: '',
				newnotifycation: '',
				unreadTotal: 0,
				conversations: [],

				actionPopup: {
					conversation: null,
					visible: false
				},
				showlogin: false,
			}
		},
		onLoad() {
			uni.hideShareMenu();
		},
		onShow() {
			// if (uni.getStorageSync('is_active')== false){
			// 	uni.showToast({
			// 		title: '该账号已被冻结，有疑问请联系客服',
			// 		icon: 'none',
			// 		duration: 2000
			// 	})
			// 	setTimeout(() => {
			// 		uni.switchTab({
			// 			url: '/pages/mine/mine'
			// 		})
			// 	}, 2000);
			// }
			if (uni.getStorageSync('hasLogin') == true) {
				this.userInfo = uni.getStorageSync('userInfo')
				// 这里判断一下她有没有换头像
					this.avatar=this.userInfo.avatar
				if (this.goEasy.getConnectionStatus() === 'disconnected') {
					this.connectGoEasy(); //连接goeasy
					// this.subscribeGroup(); //建立连接后，就应该订阅群聊消息，避免漏掉
				}
				this.goEasy.im.on(this.GoEasy.IM_EVENT.CONVERSATIONS_UPDATED, this.renderConversations); //监听会话列表变化
				this.loadConversations(); //加载会话列表
				// this.getNotifications();
			} else {
				uni.showToast({
					icon: 'none',
					title: '您还没有登陆！',
					duration: 1000
				})
				setTimeout(() => {
					this.showlogin = true
				}, 1000);
			}
			// uni.showShareMenu({
			// 	withShareTicket: true,
			// 	menus: ["shareAppMessage", "shareTimeline"]
			// })

		},
		onPullDownRefresh(e) {
			console.log("上拉")

			this.loadConversations();
		},
		beforeDestroy() {
			this.goEasy.im.off(this.GoEasy.IM_EVENT.CONVERSATIONS_UPDATED, this.renderConversations);
		},
		methods: {
			formatDate,

			connectGoEasy() {
				uni.showLoading();
				this.goEasy.connect({
					id: this.userInfo.username,
					data: {
						name: this.userInfo.nickname,
						avatar: this.avatar
					},
					onSuccess: () => {
						console.log('GoEasy connect successfully.')
					},
					onFailed: (error) => {
						console.log('Failed to connect GoEasy, code:' + error.code + ',error:' + error
							.content);
					},
					onProgress: (attempts) => {
						console.log('GoEasy is connecting', attempts);
					}
				});
			},

			// 加载最新的会话列表
			loadConversations() {
				this.goEasy.im.latestConversations({
					onSuccess: (result) => {
						uni.stopPullDownRefresh(); //上拉停止刷新
						uni.hideLoading();
						let content = result.content;
						this.renderConversations(content);
						// console.log('Conversations loadConversations ')
						// console.log(result.content)
						let unreadTotal = content.unreadTotal;
						if (unreadTotal > 0) {
							uni.setTabBarBadge({
								index: 1,
								text: unreadTotal.toString()
							});
						} else {
							uni.removeTabBarBadge({
								index: 1
							});
						}
					},
					onFailed: (error) => {
						uni.hideLoading();
						console.log('获取最新会话列表失败, error:', error);
					}
				});
			},
			async renderConversations(content) {
				this.conversations = content.conversations;
				
				// 这里需要查最新的用户信息包括网名和头像
				if(this.conversations.length>0){
					for(let i in this.conversations){
						const userInfo = {
							username: this.conversations[i].userId,
						}
						const {
							data: res
						} = await uni.$http.post('getMyInfo/', userInfo)
						if (res.code == 200) {
							this.conversations[i].data.name=res.data.nickname
							// 这里同样需要判断
								this.conversations[i].data.avatar=res.data.avatar
							// this.conversations[i].data.avatar=this.mediaUrl+res.data.avatar
							
						} else {
							uni.showToast({
								icon: 'error',
								title: res.msg
							})
						}
						// console.log(this.conversations[i])
						
						
					}
				}
				
				// console.log(this.conversations)
			},

			//     async subscribeGroup() {
			//       // let groups = restApi.findGroups(this.currentUser);
			//       // let groupIds = groups.map(item => item.id);
			// const postmsg = {
			// 	myphone:this.myphone,
			// }
			// const {data:res} = await uni.$http.post('getGroupIDs/',postmsg)
			// if(res.status==200){
			// 	// console.log('res',res);
			// 	let groupIds = res.groupIds
			// 	this.goEasy.im.subscribeGroup({
			// 	  groupIds: groupIds,
			// 	  onSuccess: function () { console.log('订阅群消息成功'); },
			// 	  onFailed: function (error) { console.log('订阅群消息失败:', error); }
			// 	});
			// }else{
			// 	console.log('接收到消息',res.msg);
			// }
			//     },
			topConversation() { //会话置顶
				this.actionPopup.visible = false;
				let conversation = this.actionPopup.conversation;
				let description = conversation.top ? '取消置顶' : '置顶';
				this.goEasy.im.topConversation({
					conversation: conversation,
					top: !conversation.top,
					onSuccess: function() {
						uni.showToast({
							title: description + '成功',
							icon: 'none'
						});
					},
					onFailed: function(error) {
						console.log(description, '失败：', error);
					}
				});
			},
			deleteConversation() {
				uni.showModal({
					content: '确认删除这条会话吗？',
					success: (res) => {
						if (res.confirm) {
							let conversation = this.actionPopup.conversation;
							this.actionPopup.visible = false;
							this.goEasy.im.removeConversation({
								conversation: conversation,
								onSuccess: function() {
									console.log('删除会话成功');
								},
								onFailed: function(error) {
									console.log(error);
								},
							});
						} else {
							this.actionPopup.visible = false;
						}
					},
				})
			},

			async chat(conversation) {
				uni.navigateTo({
					url: '/pages/conversations/privateChat?id=' + conversation.userId 
				});
				// console.log(conversation)
				// if (conversation.type === this.GoEasy.IM_SCENE.PRIVATE) {
				// 	const userInfo = {
				// 		username: conversation.userId,
				// 	}
				// 	const {
				// 		data: res
				// 	} = await uni.$http.post('getMyInfo/', userInfo)
				// 	console.log( conversation.lastMessage.payload)
				// 	if (res.code == 200) {
				// 		uni.navigateTo({
				// 			url: '/pages/conversations/privateChat?id=' + conversation.userId + '&nickname=' +
				// 				// unescape(res.data.nickname) + '&avatar=' + this.mediaUrl + res.data.avatar +
				// 				res.data.nickname + '&avatar=' + this.mediaUrl + res.data.avatar
				// 				 // 下·+'&goodsid=' + conversation.lastMessage.payload.goodsid
				// 		});
				// 	} else {
				// 		uni.showToast({
				// 			icon: 'error',
				// 			title: res.msg
				// 		})
				// 	}
				// }
			},
			// async getNotifications() {
			// 	const postmsg = {
			// 		username: this.userInfo.username,
			// 	}
			// 	const {
			// 		data: res
			// 	} = await uni.$http.post('getNotifications/', postmsg)
			// 	if (res.code == 200) {
			// 		this.notifications = res.data.notification
			// 		this.count = res.data.count
			// 		this.newnotifycation = res.data.notification[0]
			// 		// console.log('接收到消息了！',this.notifications,this.count,this.newnotifycation);
			// 	} else {
			// 		console.log('接收到消息', res.msg);
			// 	}
			// },

			noticeClick() {
				uni.navigateTo({
					url: '/pages/conversations/notifications'
				})
			},

			showAction(conversation) {
				this.actionPopup.conversation = conversation;
				this.actionPopup.visible = true;
			}
		}
	}
</script>

<style lang="scss">
	page {
		background-color: #fff;
		overflow: hidden;
	}

	.container {
		padding: 16rpx;
	}

	.noticebox {
		width: 100%;
		height: 100px;
		background-color: #fff;
		display: flex;
		align-items: center;
		padding: 0 30rpx;
		box-sizing: border-box;

		.iconbox {
			width: 120rpx;
			height: 60px;
			background-color: #6C64D0;
			display: flex;
			align-items: center;
			justify-content: center;
			border-radius: 30px;
		}

		.content {

			// display: flex;
			// flex-direction: column;
			// justify-content: space-between;
			// padding: 10px 4px;
			// margin-left: 10px;
			// font-size: 16px;
			// box-sizing: border-box;
			.box {
				font-size: 24rpx;
				width: 600rpx;
				display: flex;
				justify-content: space-between;
				padding: 4px 10px;
				color: #fff;


				text:first-child {

					width: 520rpx;
					display: flex;
					justify-content: space-between;
					margin-right: 20rpx;

				}
			}

		}
	}

	.conversations {
		box-sizing: border-box;
		display: flex;
		flex-direction: column;
		box-sizing: border-box;
		height: 100%;
	}

	.conversations .scroll-item {
		min-height: 152rpx;
		display: flex;
		align-items: center;
		background-color: #fff;
		border-radius: 12rpx;
		padding: 20rpx;
		margin: 20rpx 20rpx 0rpx;
		box-sizing: border-box;

		&.system {
			border-radius: 20rpx;
			background: rgb(238, 239, 255);
		}

		&.interact {
			border-radius: 20rpx;
			background: rgb(239, 255, 247);
		}
	}

	.conversations .scroll-item .head-icon {
		width: 100rpx;
		height: 100rpx;
		border-radius: 100%;

	}

	.conversations .scroll-item_info {
		box-sizing: border-box;
		flex: 1;
		width: 538rpx;
	}


	.conversations .item-info-top_name {
		font-size: 30rpx;
		font-weight: bold;
		color: #262628;
		margin-bottom: 10rpx;
	}

	.conversations .item-info-top_time {
		font-size: 28rpx;
		color: rgba(179, 179, 179, 0.8);
		font-family: Source Han Sans CN;
	}

	.conversations .item-info-bottom {
		height: 40rpx;
		line-height: 40rpx;
		overflow: hidden;
	}


	.item-info-bottom .item-info-top_content {
		font-size: 28rpx;
		color: #b3b3b3;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
		width: 542rpx;

	}

	.item-info-bottom .item-info-bottom_action {
		width: 50rpx;
		height: 50rpx;
		font-size: 34rpx;
		background: url("../../static/images/action.png") no-repeat center;
		background-size: 28rpx 30rpx;
	}

	.no-conversation {
		width: 100%;
		text-align: center;
		font-size: 28rpx;
		color: #9D9D9D;
		padding: 20rpx 0;

	}

	.item-head {
		width: 100rpx;
		height: 100rpx;
		overflow: hidden;
		border-radius: 100%;
		margin-right: 20rpx;
		flex-shrink: 0;
		line-height: 100rpx;
		text-align: center;

		image {
			width: 100%;
			height: 100%;
		}
	}

	.item-head_unread {
		position: absolute;
		padding: 6rpx;
		background-color: #EE593C;
		color: #FFFFFF;
		font-size: 34rpx;
		line-height: 28rpx;
		border-radius: 24rpx;
		min-width: 24rpx;
		min-height: 24rpx;
		text-align: center;
		//
		// top: 0;
		// right: 15rpx;
	}

	.action-container {
		width: 100%;
		height: 100%;
		position: fixed;
		top: 0;
		left: 0;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.action-container .layer {
		position: absolute;
		top: 0;
		left: 0;
		background: rgba(51, 51, 51, 0.5);
		width: 100%;
		height: 100%;
		z-index: 99;
	}

	.action-box {
		width: 400rpx;
		height: 240rpx;
		background: #ffffff;
		position: relative;
		z-index: 100;
		border-radius: 20rpx;
		overflow: hidden;
	}

	.action-item {
		text-align: center;
		line-height: 120rpx;
		font-size: 34rpx;
		color: #262628;
		border-bottom: 1px solid #EFEFEF;
	}

	.unread-text {
		color: #d02129;
	}
</style>